package gateway;

import io.netty.handler.codec.http.HttpMethod;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.http.client.HttpClient;
import reactor.ipc.netty.http.client.HttpClientResponse;

import java.util.HashMap;


public class MyRequestTimeGatewayFilter implements GatewayFilter, Ordered {

    private static final String REQUEST_TIME_BEGIN = "requestTimeBegin";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        exchange.getAttributes().put(REQUEST_TIME_BEGIN, System.currentTimeMillis());

        HttpClient httpClient = HttpClient.builder().build();
        Mono<HttpClientResponse> mono=  httpClient.request(HttpMethod.GET, "http://httpbin.org:80/get", request -> {
            request.addHeader("accoutn", "aaaa");
            request.sendObject(new HashMap() {{
                put("1", "2");
            }});
            return Mono.empty();
        });
        HttpClientResponse httpClientResponse = mono.block();

        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
                    if (startTime != null) {
                        System.out.println("用时：" + exchange.getRequest().getURI().getRawPath() + ": " + (System.currentTimeMillis() - startTime) + "ms");
                    }
                })
        );

    }

    @Override
    public int getOrder() {
        return 0;
    }

    public static void main(String args[]) throws InterruptedException {
        HttpClient client = HttpClient.create();
        Mono<HttpClientResponse> mono = client.get("http://baidu.com");
        //NOTE reactor.ipc.netty.http.client.MonoHttpClientResponse
        mono.subscribe(System.out::println);

        Thread.sleep(3000);
    }

}
